package com.bookstore.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bookstore.entity.dto.*;
import com.bookstore.entity.po.UserPO;
import com.bookstore.entity.pojo.R;
import com.bookstore.entity.vo.OrderVo;
import com.bookstore.service.OrderService;
import com.bookstore.service.UserService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    OrderService orderService;

    @PostMapping("login")
    public R login (@RequestBody UserDTO user) {
        QueryWrapper<UserPO> userPOQueryWrapper = new QueryWrapper<>();
        userPOQueryWrapper.eq("user_name",user.getUserName());

        UserPO one = userService.getOne(userPOQueryWrapper);
        if (one == null) {
            return R.error();
        }
        if(one.getStatus() == 1){
            return R.error("未启用");
        }
        if (one.getPassword().equals(user.getPassword())){
            return R.success(one);
        }
        return R.error();
    }

    @PostMapping("register")
    public R register (@RequestBody UserDTO user) {
        QueryWrapper<UserPO> userPOQueryWrapper = new QueryWrapper<>();
        userPOQueryWrapper.eq("user_name",user.getUserName());
        UserPO one = userService.getOne(userPOQueryWrapper);
        if (one != null) {
            return R.error("user has been exist");
        }else {
            SimpleDateFormat s  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = s.format(new Date());
            userService.save(new UserPO(user.getUserName(),user.getPassword(), format));
            return R.success();
        }
    }

    @PostMapping("test")
    public R pic( MultipartRequest file,String username) {

        for (MultipartFile fileFile : file.getFiles("file")) {
            System.out.println(fileFile);

            InputStream inputStream = null;
            try {
                inputStream = fileFile.getInputStream();
                System.out.println(inputStream.available());

                byte[] bytes = new byte[inputStream.available()];
                inputStream.read(bytes,0,inputStream.available());
                BASE64Encoder base64Encoder = new BASE64Encoder();
                System.out.println(fileFile.getOriginalFilename());
                int i = fileFile.getOriginalFilename().lastIndexOf(".");
                String k = fileFile.getOriginalFilename().substring(i + 1,fileFile.getOriginalFilename().length()).equals("jpg")?"jpeg":fileFile.getOriginalFilename().substring(i,fileFile.getOriginalFilename().length());
                String prefix = "data:image/" + k + ";base64,";
                String encode = base64Encoder.encode(bytes);
                UserPO userPO = new UserPO();
                userPO.setHeadPortrait(prefix + encode);
                QueryWrapper<UserPO> userPOQueryWrapper = new QueryWrapper<>();
                userPOQueryWrapper.eq("user_name",username);
                boolean update = userService.update(userPO, userPOQueryWrapper);
                return R.success(update?prefix + encode:"");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return R.success();
    }
    @PostMapping("order")
    public R order (@RequestBody OrderDTO orderDTO) {
        boolean enoughMoney = userService.enoughMoney  (orderDTO.getUserName(),
                                                        orderDTO, orderDTO.getNum(),
                                                        orderDTO.getBookId());
        if (!enoughMoney){
            return R.error("你的钱不够");
        }

        com.bookstore.entity.po.OrderPO orderPO = new com.bookstore.entity.po.OrderPO();
        orderPO.setUserName(orderDTO.getUserName());
        orderPO.setBookId(orderDTO.getBookId());
        orderPO.setLogistics("未发货");
        orderPO.setNums(orderDTO.getNum());
        orderPO.setSigned(OrderService.NOT_SHIPPED);
        orderPO.setCreateTime(new Date());

        boolean save = orderService.save(orderPO);
        return save?R.success():R.error();
    }

    @PostMapping("orderGroup")
    public R order (@RequestBody OrderGroupDTO orderDTOs) {
        System.out.println(orderDTOs);
        OrderDTO[] list = orderDTOs.getList();

        if(list.length == 0){
            return R.success();
        }
        if(!userService.enoughMoneyGroup(list[0].getUserName(),orderDTOs.getAllPrice())){
            return R.error("钱不够");
        }
        com.bookstore.entity.po.OrderPO[] orderPOS = new com.bookstore.entity.po.OrderPO[list.length];
        for (int i = 0; i < orderPOS.length; i++) {
            orderPOS[i] = new com.bookstore.entity.po.OrderPO(null,
                    list[i].getUserName(),
                    list[i].getBookId(),
                    list[i].getNum(),
                    OrderService.NOT_SHIPPED,
                    "未发货",
                    new Date());
        }
        boolean b = orderService.saveBatch(Lists.list(orderPOS));

        return b?R.success():R.error();
    }




    @PostMapping("getUnsignedOrder")
    public R getUnsignedOrder (@RequestBody UserDTO userDTO) {
        List<OrderVo> unsignedOrder = orderService.getUnsignedOrder(userDTO.getUserName());
        return R.success(unsignedOrder);
    }
    @PostMapping("getSignedOrder")
    public R getSignedOrder (@RequestBody UserDTO userDTO) {
        List<OrderVo> unsignedOrder = orderService.getSignedOrder(userDTO.getUserName());
        return R.success(unsignedOrder);
    }
    @GetMapping("signed")
    public R signed (int id) {
        com.bookstore.entity.po.OrderPO orderPO = new com.bookstore.entity.po.OrderPO();
        orderPO.setId(id);
        orderPO.setSigned(OrderService.SINGED);
        orderPO.setLogistics("派送成功");
        boolean b = orderService.updateById(orderPO);
        return b ? R.success() : R.error();
    }

    @PostMapping("changeName")
    public R changeName(@RequestBody UserNameDTO userNameDTO) {
        if(userNameDTO.getOldName().equalsIgnoreCase("") || userNameDTO.getNewName().equals("")){
            return R.error("输入点东西呗");
        }
        QueryWrapper<UserPO> qw = new QueryWrapper<UserPO>().eq("user_name", userNameDTO.getNewName());
        UserPO one = userService.getOne(qw);
        if(one != null) {
            return R.error("已经被被人抢占先机");
        }
        UserPO userPO = new UserPO();
        userPO.setUserName(userNameDTO.getNewName());
        boolean done = userService.update(userPO, new QueryWrapper<UserPO>().eq("user_name", userNameDTO.getOldName()));
        return done?R.success():R.error("出错了");
    }

    @PostMapping("changeAddr")
    public R changeName(@RequestBody UserAddrDTO userAddrDTO) {
        if(userAddrDTO.getUserName().equalsIgnoreCase("") || userAddrDTO.getAddr().equals("")){
            return R.error("输入点东西呗");
        }
        UserPO userPO = new UserPO();
        userPO.setShippingAddress(userAddrDTO.getAddr());
        boolean done = userService.update(userPO, new QueryWrapper<UserPO>().eq("user_name", userAddrDTO.getUserName()));
        return done?R.success():R.error("出错了");
    }

    @PostMapping("changePasswd")
    public R changeName(@RequestBody UserPasswdDTO passwdDTO) {
        if(passwdDTO.getUserName().equalsIgnoreCase("") || passwdDTO.getOldPasswd().equals("")|| passwdDTO.getNewPasswd().equals("")){
            return R.error("输入点东西呗");
        }
        UserPO one = userService.getOne(new QueryWrapper<UserPO>().eq("user_name", passwdDTO.getUserName()));
        if (one == null) {
            return R.error("错误！");
        }
        if (!one.getPassword().equals(passwdDTO.getOldPasswd())){
            return R.error("错误！");
        }

        UserPO userPO = new UserPO();
        userPO.setPassword(passwdDTO.getNewPasswd());
        boolean done = userService.update(userPO, new QueryWrapper<UserPO>().eq("user_name", passwdDTO.getUserName()));
        return done?R.success():R.error("出错了");
    }

    @PostMapping("changeRealName")
    public R changeRealName(@RequestBody UserAddrDTO userAddrDTO) {
        if(userAddrDTO.getUserName().equalsIgnoreCase("") || userAddrDTO.getRealName().equals("")){
            return R.error("输入点东西呗");
        }
        UserPO userPO = new UserPO();
        userPO.setRealName(userAddrDTO.getRealName());
        boolean done = userService.update(userPO, new QueryWrapper<UserPO>().eq("user_name", userAddrDTO.getUserName()));
        return done?R.success():R.error("出错了");
    }
    @PostMapping("changePhoneNumber")
    public R changePhoneNumber(@RequestBody UserAddrDTO userAddrDTO) {
        if(userAddrDTO.getUserName().equalsIgnoreCase("") || userAddrDTO.getPhoneNumber().equals("")){
            return R.error("输入点东西呗");
        }
        UserPO userPO = new UserPO();
        userPO.setPhoneNumber(userAddrDTO.getPhoneNumber());
        boolean done = userService.update(userPO, new QueryWrapper<UserPO>().eq("user_name", userAddrDTO.getUserName()));
        return done?R.success():R.error("出错了");
    }

    @PostMapping("adminLogin")
    public R adminLogin (@RequestBody UserDTO userDTO) {
        UserPO one = userService.getOne(new QueryWrapper<UserPO>().eq("role", "admin").eq("user_name", userDTO.getUserName()));
        if (one == null) {
            return R.error("没有这个用户");
        }
        if (one.getPassword().equals(userDTO.getPassword())){
            return R.success(one);
        }
        return R.error("密码错误");
    }

}
